<?php
namespace App\Utils;

use App\Models\MUser;

/**
 *树形结构帮助类
 */
class TreeUtil
{
    /**
     * 检查报单中心是否可用
     *
     * @return 如果可用返回此报单中心对象，否则返回Null
     */
    public static function checkBdzx($username)
    {
        $bdzx = MUser::where('username', $username)
            ->where('ok_status', MUser::$STATUS_ACTIVATED)
            ->where('bdzx_status', MUser::$BDZX_YES)->first();

        return $bdzx;
    }

    /**
     * 检查推荐人是否可用
     *
     * @return 如果可用返回此推荐人对象，否则返回Null
     */
    public static function checkPuser($username)
    {
        $puser = MUser::where('username', $username)
            ->where('ok_status', MUser::$STATUS_ACTIVATED)->first();

        return $puser;
    }

    /**
     * 检查节点是否可用
     *
     * @return 如果可用返回此节点对象，否则返回Null
     */
    public static function checkNuser($username)
    {
        $nuser = MUser::where('username', $username)
            ->where('ok_status', MUser::$STATUS_ACTIVATED)->first();

        return $nuser;
    }

    /**
     * 获取指定节点人的安插位置
     *
     * @return 返回可以安插的位置。-1代表节点位置已满
     */
    public static function getNodeAddr($uid)
    {
        $childs = MUser::where('nid', $uid)->get();
        $chain = "->";
        foreach ($childs as $c) {
            if ($c->addr == MUser::$ADDR_A) {
                $chain .= "A";
            } elseif ($c->addr == MUser::$ADDR_B) {
                $chain .= "B";
            }
        }

        if (!strpos($chain, "A")) {
            return MUser::$ADDR_A;
        } elseif (!strpos($chain, "B")) {
            return MUser::$ADDR_B;
        }else{
            return MUser::$ADDR_NO;
        }

    }

    /**
     *获取到当前的根节点
     */
    public static function getRootNode()
    {
        $root = MUser::where('nid', 0)->first();
        return $root;
    }
}